package com.module.ble.hDu

import android.util.Log
import com.common.app.data.bean.KeyEvents
import com.common.app.utls.TimeUtils.getTimeDateLong
import com.common.app.utls.TimerUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.utils.JsonUtils
import com.common.base.utils.LogUtils
import com.common.base.utils.MathUtil
import com.eiot.ringsdk.bean.SportRecord
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.data.bean.HduCurSportData
import com.module.ble.db.table.UserBloodOxygen
import com.module.ble.db.table.UserBodyTemperature
import com.module.ble.db.table.UserHeartRate
import com.module.ble.hDu.HDuSendCommandManage.openHeartAndBloodMode
import com.module.ble.listener.CusSynthesisHealthExpandListener
import com.module.ble.listener.CusSportMonitorDataExpandListener
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.CommonCusHealthType
import com.module.ble.utils.HeartRateFrequencyHDu
import java.util.Timer
import java.util.TimerTask
import kotlin.math.abs


class SportMonitorTask: CusSynthesisHealthExpandListener,CusSportMonitorDataExpandListener {

    private val TAG = "SportMonitorTask"

    var hudDuringExercise = false

    var mSportId: Long = -1
    var mSportType: Int = -1


    private var mTotalSteps = 0L // 运动步数
    private var mTotalCalorie = 0L // 卡路里，单位千卡
    private var mTotalDistance = 0L // 距离，单位米
    private var mLatestHeartBeatValue = 0 // 最近一次心率值
    private var mLatestHeartBeatTime = 0L // 最近一次心率时间

    private val mSportDataList = arrayListOf<HduCurSportData>()
    private var mLastSportItem: HduCurSportData? = null
    private var curHrList= arrayListOf<Int>()
    private var curBoList= arrayListOf<Int>()

    private var timerTask: TimerTask? = null//定时器

    init {
        AizoSDKUtil.addSynthesisHealthExpandListener(this)
        AizoSDKUtil.addSportMonitorDataExpandListener(this)
        timerTask = object : TimerTask() {
            override fun run() {
                hudDuringExercise.yes {
                    doOnIOThread {
                        openHeartAndBloodMode()
                    }
                }
            }
        }
        Timer().scheduleAtFixedRate(timerTask, 0, 60000)//一分钟跑一次
    }

    /**
     * 销毁监控任务，移除所有监听器
     */
    fun destroy() {
        AizoSDKUtil.removeSynthesisHealthExpandListener(this)
        AizoSDKUtil.removeSportMonitorDataExpandListener(this)
        timerTask?.cancel()
        timerTask = null
    }

    override fun sportStart(result: Boolean, sportId: Long, ringFirm: String) {
        hudDuringExercise = true
    }

    override fun sportPause(result: Boolean) {
        hudDuringExercise = false
    }

    override fun sportResume(result: Boolean) {
        hudDuringExercise = true
    }

    override fun sportStop(result: Boolean) {
        openHeartAndBloodMode()
        hudDuringExercise = false

        doOnIOThread {
            saveData()
        }
    }

    override fun sportInfo(
        type: Int,
        timestamp: Long,
        step: Int,
        distance: Int,
        cal: Int,
        cursleeptime: Int,
        totalrunningtime: Int,
        teptime: Int
    ) {
        // 0 是运动信息，1是跑步信息

        if (type != 0) return

        if (timestamp < mSportId)  return

        doOnIOThread {
            hudDuringExercise.yes {
                if (mLastSportItem == null) {
                    mLastSportItem = HduCurSportData(mSportId, timestamp, step, cal, distance)
                    Log.i(TAG, "HDu-sdk sportInfo----mLastSportItem->${JsonUtils.toJson(mLastSportItem!!)}")
                    return@doOnIOThread
                }

                mTotalSteps += (step - mLastSportItem!!.step)
                mTotalCalorie += (cal - mLastSportItem!!.calorie)
                mTotalDistance += (distance - mLastSportItem!!.dist)

                LogUtils.e(TAG, "HDu-sdk sportInfo->${type}---${timestamp}---步数：${step}---距离：${distance}---千卡：${cal}---当前睡眠时间（秒）：${cursleeptime}---当前运动总时间：${totalrunningtime}---当前记步时间：${teptime}---")
                LogUtils.e(TAG, "HDu-sdk sportInfo2->${type}---${timestamp}---节点总步数：${mTotalSteps}---节点总距离：${mTotalDistance}---节点总千卡：${mTotalCalorie}---当前睡眠时间（秒）：${cursleeptime}---当前运动总时间：${totalrunningtime}---当前记步时间：${teptime}---")
                val heartBeat = if (abs(timestamp - mLatestHeartBeatTime) < 5) {
                    mLatestHeartBeatValue
                } else 0

                var curNodeDuration = 0L //当前节点运动时长，单位秒
                mSportDataList.isNullOrEmpty().yes {
                    curNodeDuration = ((mLastSportItem?.time?:0)/1000) - (mSportId/1000)//当前节点记录时间戳减运动开始时间戳
                }.otherwise {
                    curNodeDuration = ((mSportDataList.last().time)/1000) - (mSportId/1000)
                }
                // 计算实时配速：秒/千米
                var pace = 0.00
                if (mTotalDistance > 0) {
                    // 将毫秒转换为秒，距离转换为千米，然后计算配速
//                ((curNodeDuration / 1000) / (curNodeDistance / 1000)).toFloat()
                    LogUtils.e(TAG, "HDu-sdk MathUtil.div9->${curNodeDuration}---${MathUtil.div4(mTotalDistance.toString(),"1000",false)}---")
                    pace = MathUtil.div9(MathUtil.div4(mTotalDistance.toString(),"1000",false),curNodeDuration.toString())
                    LogUtils.e(TAG, "HDu-sdk MathUtil.div92->时速：${pace}---")
                }

                val item = HduCurSportData(
                    sportId = mSportId,
                    time = timestamp,
                    step = mTotalSteps.toInt(),
                    calorie = mTotalCalorie.toInt(),
                    dist = mTotalDistance.toInt(),
                    hr = heartBeat,
                    pace = pace,//实时配速，单位：秒/千米
                )

                mSportDataList.add(item)
                saveData()
            }
        }
    }

    override fun onLatestHr(value: Int, macStr: String, time: Long) {
    }

    override fun onHeartRateDataListResult(result: List<UserHeartRate>) {
    }

    override fun getLatestBloodOxygen(value: Int, macStr: String, time: Long) {
    }

    override fun onBloodOxygenDataListResult(result: List<UserBloodOxygen>) {
        hudDuringExercise.yes {
        }
    }

    override fun onLatestBodyTemper(value: Float, macStr: String, time: Long) {
    }

    override fun onBodyTemperDataListResult(result: List<UserBodyTemperature>) {
    }

    override fun onMeasureResult(
        result: Boolean,
        type: Int,
        time: Long,
        heartRate: Int,
        bloodOxygen: Int,
        bodyTemp: Float,
        envTemp: Float
    ) {
        LogUtils.e(TAG, "HDu-sdk onMeasureResult->${result}---${type}---${time}---${heartRate}---${bloodOxygen}---${bodyTemp}---${envTemp}---")

        when (type) {
            CommonCusHealthType.HEARTRATE.value -> {
                hudDuringExercise.yes {
                    mLatestHeartBeatValue = heartRate
                    mLatestHeartBeatTime = time
                    curHrList.add(heartRate)
                }
            }

            CommonCusHealthType.BLOODOXYGEN.value -> {
                hudDuringExercise.yes {
                    curBoList.add(bloodOxygen)
                }
            }
            CommonCusHealthType.BODYTEMP.value -> {
            }
        }
    }

    fun getSportLiveData(callback: ((Double, Int, Double, Int) -> Unit)? = null){
        callback?.invoke((mTotalDistance / 1000).toDouble(),
            if (curHrList.isNullOrEmpty()) 0 else curHrList.average().toInt(),
            mTotalCalorie.toDouble(),
            mTotalSteps.toInt()
        )
        LogUtils.e(TAG, "HDu-sdk getSportLiveData-> 距离(米)：${mTotalDistance}---心率：${if (curHrList.isNullOrEmpty()) 0 else curHrList.last()}---千卡：${mTotalCalorie.toDouble()}---步数：${mTotalSteps.toInt()}---")
    }

    private fun saveData(){
        val mSportRecord = SportRecord()
        mSportRecord.sportId = mSportId
        mSportRecord.endTime = getTimeDateLong()
        mSportRecord.sportType = mSportType
        mSportRecord.device = AizoSDKUtil.curMac?:""

        mSportRecord.steps = mTotalSteps
        mSportRecord.duration = mTotalDistance
        mSportRecord.calorie = mTotalCalorie.toFloat()
        mSportRecord.distance = mTotalDistance.toFloat()

        mSportRecord.avgHr = curHrList.average().toInt()//平均心率
        mSportRecord.minHr = curHrList.minOrNull() ?: 0//最小心率
        mSportRecord.maxHr = curHrList.maxOrNull() ?: 0//最大心率

        // 从mSportDataList中获取最大pace和最小pace
        val paceList = mSportDataList.map { it.pace }.filter { it > 0 } // 过滤掉pace为0的数据
        mSportRecord.avgPace = if (paceList.isNotEmpty()) paceList.average().toFloat() else 0f // 平均配速
        mSportRecord.maxPace = (paceList.maxOrNull() ?: 0).toFloat() // 最大配速（最慢）
        mSportRecord.minPace = (paceList.minOrNull() ?: 0).toFloat() // 最小配速（最慢）

        AizoSDKUtil.saveSportRecord(mSportRecord)
    }
}
